package com.edu.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @作者 five-five
 * @创建时间 2021/6/15
 */
public class PhoneCode {

    public static void main(String[] args) {
        System.out.println(getCode());
    }

    /**
     * 验证码校验
     *
     * @param phone 电话号码
     * @param code  验证码
     */
    public static void getRedisCode(String phone, String code) {
        Jedis jedis = new Jedis("39.104.54.209", 6379);
        //从redis中得到key
        String countKey = "VerifyCode" + phone + ":count";
        String codeKey = "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);
        //进行判断
        if (redisCode.equals(code)) {
            System.out.println("成功");
        } else {
            System.out.println("失败");
        }
    }


    /**
     * 设置每个手机只能发送三次，验证码放到redis中，设置过期时间
     *
     * @param phone 电话号码
     */
    public static void verifyCode(String phone) {
        Jedis jedis = new Jedis("39.104.54.209", 6379);
        String countKey = "VerifyCode" + phone + ":count";
        String codeKey = "VerifyCode" + phone + ":code";
        String count = jedis.get(countKey);
        if (count == null) {
            //没有发送次数
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(count) <= 2) {
            //发送次数+1
            jedis.incrBy(countKey, 1);
        } else if (Integer.parseInt(count) > 2) {
            //发送三次了
            System.out.println("今天的发送次数已经超过三次");
            jedis.close();
        }
        String vcode = getCode();
        jedis.setex(codeKey, 24 * 60 * 60, vcode);
    }

    /**
     * @return 返回一个6位的验证码
     */
    public static String getCode() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        return code;
    }
}
